<?php
include_once 'data.php';

function save_export_files ($filename, $files, $timestamp) {
    $export_files = array ();
    $export_files['timestamp'] = $timestamp;
    $export_files['files'] = $files;
    $export_files_content = serialize ($export_files);
    file_put_contents($filename, $export_files_content, LOCK_EX);
}

if (isset($_GET['file'])) {
	if (!isset($_SESSION['session_clipboard'])) {
		$_SESSION['session_clipboard'][] = $_GET['file'];
		echo "added";
	} else {
		if (!in_array($_GET['file'], $_SESSION['session_clipboard'])) {
			$_SESSION['session_clipboard'][] = $_GET['file'];
			$_SESSION['session_clipboard'] = array_unique($_SESSION['session_clipboard']);
			echo "added";
		} else {

                  $cached_files_file = $temp_dir.DIRECTORY_SEPARATOR.'lib_'.session_id().DIRECTORY_SEPARATOR.'exportfiles.txt';

                  if(is_readable($cached_files_file)) {
                      $export_files_content = file_get_contents($cached_files_file);
                      $export_files_array = unserialize ($export_files_content);
                      $export_files_timestamp = $export_files_array['timestamp'];
                      $export_files = $export_files_array['files'];
                  }

			$key = array_search($_GET['file'], $_SESSION['session_clipboard']);
			unset($_SESSION['session_clipboard'][$key]);
                     if (isset($_GET['selection']) && $_GET['selection'] == 'clipboard') {
                        $id = array_search($_GET['file'], $export_files);
                        if ($id !== false) {
                            unset($export_files[$id]);
                            $export_files = array_values($export_files);
                            save_export_files ($cached_files_file, $export_files, time());
                        }
                     }
			echo "removed";
		}
	}
}
?>